import { appInfos, officialMiniProgramAppids } from '@/constants/AppInfo'
import i18n from '@/i18n'

import { useAccountStore } from '@/store/account'
import { getSharing } from '@/api/appliance'
import dayjs from 'dayjs'
import { TrackType, trackEvent } from '@/dataReport/tracks'
import { safeTrack } from '@/dataReport/dataReportUtil'
import { usePageEffect, type PageEffectOptions } from './composition/usePageEffect'
import { stubFalse, toNumber } from 'lodash'
import {
  checkBlutoothPermission,
  OS_SYSTEM_LOCATION_PERMISSION,
  APPLICATION_LOCATION_PERMISSION,
  WXMP_LOCATION_PERMISSION,
} from './basicHelper'
import netconfig from '@/config/netconfig'
import { encryptUserPhone } from '@/api/account'

const accountStore = useAccountStore()

export function login(): Promise<UniNamespace.LoginRes> {
  return new Promise<UniNamespace.LoginRes>((resolve, reject) => {
    uni.login({
      success: (result) => resolve(result),
      fail: () => reject(new Error('Login failed')),
    })
  })
}

/**
 * 操作防抖方法 (Promise级)
 */
type ActionDebounceOptions<This = any, TResult = any, TError = any, TArgs extends any[] = any[]> = {
  // pre回调 最先执行 (不算在超时时间内，只会调一次【但无论是否超时 都会被调用】)
  pre?: (this: This, ...args: TArgs) => Promise<any>
  // call回调 在Promise状态为fullfilled前，只会调一次【但无论是否超时 都会被调用】
  call: (this: This, ...args: TArgs) => Promise<TResult>
  // then回调 只会在【超时前 且 call回调执行成功后】调用
  then?: (this: This, value: TResult) => Promise<TResult> | TResult | Promise<void> | void
  // catch回调 只会在【超时前 且 call回调执行失败后】调用
  catch?: (this: This, error: TError) => Promise<TError> | TError | void
  // finally回调 只会在【超时前】调用
  finally?: (this: This) => any

  /**
   * 时间配置 (单位: ms)
   */
  // 设置超时时间 (超时后 关闭loading)
  timeout?: number | null
  // // 设置节流时间 (无论方法调用是否结束 节流时间范围内 不再触发call then catch finally方法)
  // throttle?: number | null
  // 设置方法调用完成后的延迟时间 (延迟时间范围内 不再触发call then catch finally方法)
  delay?: number | null

  /**
   * 加载配置
   */
  // 是否显示loading (只配置loadingText也会显示loading)
  showLoading?: boolean
  // loading提示文本
  loadingText?: string
}

const DefaultActionDebounceOptions: Partial<ActionDebounceOptions> = {
  timeout: 3000,
}
export const DebouncedWarning = 'Warning: Promise action debounced'
export function actionDebounce<This = any, TResult = any, TError = any, TArgs extends any[] = any[]>(
  debounceOptions?: ActionDebounceOptions<This, TResult, TError, TArgs>
): (this: This, ...args: TArgs) => Promise<TResult | void> {
  const options: ActionDebounceOptions<This, TResult, TError, TArgs> = {
    ...(DefaultActionDebounceOptions as ActionDebounceOptions),
    ...debounceOptions,
  }
  const needShowLoading = options.showLoading || options.loadingText
  const loadingHandler = needShowLoading
    ? (action: () => Promise<TResult | void>) =>
        showLoading(action, options.loadingText || i18n.global.t('APP.Common.Loading.Text'))
    : (action: () => Promise<TResult | void>) => action()
  const onTimeout = needShowLoading ? () => _hideLoading() : () => {}

  /**
   * 防抖状态
   */
  let isPending = false

  return async function () {
    if (isPending) {
      console.warn(DebouncedWarning)
      return Promise.resolve()
    }

    isPending = true

    // 入参
    const args = Array.from(arguments) as TArgs

    try {
      await options.pre?.apply(this, args)
    } catch (e) {
      console.error(e)
    }

    // const promiseTasks: Promise<TResult>[] = [options.call.apply(this, args)]
    // if (typeof options.timeout === 'number') {
    //   const timeoutTask = _getTimeoutPromise<TResult>(
    //     options.timeout,
    //     new Error(`Fatal: Timeout (${options.timeout}ms)`)
    //   )
    //   promiseTasks.push(timeoutTask)
    // }

    return loadingHandler(async () => {
      try {
        // 设置超时
        if (typeof options.timeout === 'number') {
          setTimeout(() => {
            isPending = false
            onTimeout()
          }, options.timeout)
        }

        // let ret = await Promise.race(promiseTasks)
        let ret = await options.call.apply(this, args)

        // 设置延迟
        setTimeout(() => {
          isPending = false
        }, options.delay || 0)

        if (options.then) {
          ret = (await options.then.call(this, ret)) || ret
        }
        options.finally?.call(this)

        return ret
      } catch (e) {
        if (e === DebouncedWarning) {
          console.warn(DebouncedWarning)
          return Promise.resolve()
        }

        console.error(e)

        setTimeout(() => {
          isPending = false
        }, options.delay || 0)

        e = options.catch?.call(this, e as TError) || e
        options.finally?.call(this)

        return Promise.resolve()
      }
    })
  }
}
// function _getTimeoutPromise<TResult, TError = any>(timeout: number, error: TError): Promise<TResult> {
//   return new Promise((_, reject) => {
//     setTimeout(() => reject(error), timeout)
//   })
// }

/**
 * 通用 Loading 方法
 */
// 为解决多次调用异步方法 添加执行记录 所有方法执行完毕再关闭loading
const loadingRecords = new Set()
export async function showLoading<T>(loader: () => Promise<T>, message?: string | null): Promise<T> {
  let title: string | undefined
  if (message !== null) {
    title = message || i18n.global.t('APP.Common.Loading.Text')
  }

  uni.showLoading({
    title,
    mask: true,
  })
  loadingRecords.add(loader)
  try {
    const ret = await loader()
    loadingRecords.delete(loader)
    _hideLoading()
    return ret
  } catch (e) {
    console.error(e)
    loadingRecords.delete(loader)
    _hideLoading()
    return Promise.reject(e)
  }
}
function _hideLoading() {
  if (loadingRecords.size === 0) uni.hideLoading()
}

// 单次监听方法 (触发监听后清除监听)
export function onceObserve<TValue>(trigger: () => TValue, onChange?: (value: TValue) => void): Promise<TValue> {
  return new Promise((resolve, reject) => {
    const stopWatch = watch(trigger, (value) => {
      try {
        onChange?.(value)
        resolve(value)
      } catch (e) {
        console.error(e)
        reject(e)
      }
      stopWatch()
    })
  })
}
// 单次表达式监听方法 (触发watchEffect监听且表达式成立时清除监听)
export function onceExpressionObserve(matcher: () => boolean): Promise<void> {
  return new Promise((resolve) => {
    const stopWatch = watchEffect(() => {
      if (matcher()) {
        stopWatch()
        resolve()
      }
    })
  })
}
// Promise化的nextTick方法 用于等待数据刷新视图等
export function nextTickPromise(): Promise<void> {
  return new Promise((resolve) => {
    nextTick(() => resolve())
  })
}

type OmitCallbackHell<Options> = Omit<Options, 'success' | 'fail' | 'complete'>
/**
 * 显示底部弹出选项
 */
export function showActionSheet(
  options: OmitCallbackHell<UniNamespace.ShowActionSheetOptions>
): Promise<UniNamespace.ShowActionSheetRes> {
  return new Promise((resolve, reject) => {
    uni.showActionSheet({
      ...options,
      success: (res) => resolve(res),
      fail: (e) => reject(e),
    })
  })
}

type NativeCallbacks = {
  onConfirm: () => Promise<void>
  onCancel: () => Promise<void>
}
export function showModal(
  options: OmitCallbackHell<UniNamespace.ShowModalOptions>,
  nativeCallbacks?: Partial<NativeCallbacks>
): Promise<UniNamespace.ShowModalRes['content']> {
  return new Promise((resolve, reject) => {
    uni.showModal({
      ...options,
      success: async (res) => {
        if (res.confirm) {
          try {
            await nativeCallbacks?.onConfirm?.()
          } catch (e) {
            console.error(e)
          }
          resolve(res.content)
        } else {
          try {
            await nativeCallbacks?.onCancel?.()
          } catch (e) {
            console.error(e)
          }
          reject(res.errMsg)
        }
      },
      fail: (e) => reject(e),
    })
  })
}

type BaseDataType = string | number | boolean | null | undefined
export function getNavigateUrl(url: string, params?: Record<string, BaseDataType>) {
  let query = ''
  if (params) {
    const queryKeywords = Object.entries(params)
      .reduce<string[]>((query, [key, value]) => {
        if (value !== void 0) {
          const transformedValue = value === null ? 'null' : encodeURIComponent(value)
          query.push(`${key}=${transformedValue}`)
        }
        return query
      }, [])
      .join('&')
    query = `?${queryKeywords}`
  }
  return url + query
}

export function toPage(
  url: string,
  params?: Record<string, BaseDataType>
): Promise<UniNamespace.NavigateToSuccessOptions> {
  return new Promise((resolve, reject) => {
    uni.navigateTo({
      url: getNavigateUrl(url, params),
      success: (res) => resolve(res),
      fail: (err) => reject(err),
    })
  })
}

export function toHome(params?: Record<string, BaseDataType>) {
  return new Promise((resolve, reject) => {
    uni.reLaunch({
      url: getNavigateUrl('/pages/navigator/index/index', params),
      success: (res) => resolve(res),
      fail: (err) => reject(err),
    })
  })
}
export function redirectTo(url: string, params?: Record<string, BaseDataType>): Promise<void> {
  return new Promise((resolve, reject) => {
    uni.redirectTo({
      url: getNavigateUrl(url, params),
      success: (res) => resolve(res),
      fail: (err) => reject(err),
    })
  })
}
export function reLaunch(url: string, params?: Record<string, BaseDataType>): Promise<void> {
  return new Promise((resolve, reject) => {
    uni.reLaunch({
      url: getNavigateUrl(url, params),
      success: (res) => resolve(res),
      fail: (err) => reject(err),
    })
  })
}
export function goBackPage(options?: OmitCallbackHell<UniNamespace.NavigateBackOptions>): Promise<void> {
  return new Promise((resolve, reject) => {
    uni.navigateBack({
      ...options,
      success: (res) => resolve(res),
      fail: (err) => reject(err),
    })
  })
}

// 一次性消息订阅 (无论用户是否同意都resolve)
export function requestSubscribeUsingComplete(tmplIds: string[]) {
  return new Promise<void>((resolve) => {
    // 消息订阅ID使用设备消息ID
    wx.requestSubscribeMessage({
      tmplIds,
      success: (res) => {},
      fail: (fail) => {},
      complete: () => resolve(),
    })
  })
}
export function requestSubscribe(tmplIds: string[]) {
  return new Promise((resolve, reject) => {
    // 消息订阅ID使用设备消息ID
    wx.requestSubscribeMessage({
      tmplIds,
      success: (res) => resolve(res),
      fail: (e) => reject(e),
    })
  })
}

export function useUniEvent<TArg>(eventName: string, listener: (...args: TArg[]) => void, options?: PageEffectOptions) {
  return usePageEffect(
    {
      onInvoke: () => uni.$on(eventName, listener),
      onUnload: () => uni.$off(eventName, listener),
    },
    options
  )
}

export function getImageInfo(src: string): Promise<UniNamespace.GetImageInfoSuccessData> {
  return new Promise((resolve, reject) => {
    uni.getImageInfo({
      src,
      success: (res) => resolve(res),
      fail: (e) => reject(e),
    })
  })
}

export async function jumpMP(
  appId: string,
  path: string,
  params: Record<string, string | number | boolean> = {},
  buttonId?: string | undefined
) {
  const appInfo = appInfos[appId]
  if (!path) {
    path = appInfo.path
  }
  //拦截OMP小程序给其跳转参数加上手机号密文和签名参数
  if (officialMiniProgramAppids.includes(appId)) {
    const res = await encryptUserPhone()
    if (res.code == 0) {
      params = {
        ...params,
        sign: res.data.sign,
        phoneData: res.data.encryptDate,
      }
    }
  }
  //西门子家电官方服务小程序的话，改成往西门子家电小程序跳转
  if (appId == 'wx369c3977e8f0bc7d') {
    appId = 'wx00e2750add150103'
  }
  const appendSign = path.includes('?') ? '&' : '?'
  path = [
    path,
    Object.entries({
      ...params,
      utm_source: appInfo.utm_source,
      utm_medium: appInfo.utm_medium,
    })
      .map(([key, value]) => `${key}=${encodeURIComponent(value)}`)
      .join('&'),
  ].join(appendSign)
  return toMiniProgram(
    {
      appId,
      path,
    },
    buttonId
  )
}

export function requireModule<T>(path: string): Promise<T> {
  // 根路径
  if (/^\//.test(path)) {
    path = '..' + path
  }
  return new Promise((resolve, reject) => {
    require(path, (mod) => {
      resolve(mod as T)
    }, (err) => {
      reject(err)
      console.error(`path: ${err.mod}, ${err.errMsg}`)
    })
  })
}

/**
 * 跳转小程序
 */
function toMiniProgram(
  options: OmitCallbackHell<UniNamespace.NavigateToMiniProgramOptions>,
  buttonId?: string | undefined
): Promise<any> {
  return new Promise<void>((resolve, reject) => {
    uni.navigateToMiniProgram({
      ...options,
      envVersion: netconfig.ENV == 'PCN' ? 'release' : 'trial',
      success: (res) => {
        safeTrack(() => {
          trackEvent(
            'open_3rdParty_mp',
            { landing_path: options.path, mp_app_id: options.appId, result: true },
            TrackType.BusinesssScene,
            buttonId
          )
        })
        resolve(res)
      },
      fail: (e) => {
        safeTrack(() => {
          trackEvent(
            'open_3rdParty_mp',
            { landing_path: options.path, mp_app_id: options.appId, result: false },
            TrackType.BusinesssScene,
            buttonId
          )
          reject(e)
        })
      },
    })
  })
}

/**
 * 按钮振动
 */
export function vibrate() {
  uni.vibrateShort({ type: 'medium' })
}

/**
 * 跳转页面传参
 */
export function callEventSender<T>(channel: UniNamespace.EventChannel, eventName: string, arg: T) {
  channel.emit(eventName, arg as any)
}
export function useEventReceiver<T>(eventName: string, callback: (arg: T) => void) {
  const instance = getCurrentInstance()
  let mpInstance: any | null = null
  onMounted(() => {
    mpInstance = instance?.proxy as any
    if (!mpInstance) {
      console.warn('Miniprogram instance does not exist')
      return
    }
    const eventChannel = mpInstance.getOpenerEventChannel()
    eventChannel.on(eventName, callback)
  })
}

export function getLatestPage() {
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  return currentPage
}

export function getPageQuery<QueryOptions extends Record<string, any> = Record<string, any>>(
  query?: Record<string, string>,
  jsonFields: (keyof QueryOptions)[] = []
): QueryOptions {
  if (!query) {
    const currentPage = getLatestPage()
    if (!currentPage) return {} as QueryOptions
    query = ((currentPage as any).options || {}) as Record<string, string>
  }

  const decodedQuery = Object.entries(query).reduce<Record<string, any>>((params, [key, rawValue]) => {
    let value: any = decodeURIComponent(rawValue)
    if (jsonFields.includes(key)) {
      try {
        value = JSON.parse(rawValue)
      } catch (e) {}
    }
    params[key] = value
    return params
  }, {})
  return decodedQuery as QueryOptions
}

export function toTargetMiniProgramDetailPage(
  appliance_type: string,
  params: Record<string, string | number | boolean> = {},
  button_id?: string
): Promise<void> {
  let appId = 'wx4a7a485f483fd236'
  const appInfo = appInfos[appId]
  let path = appInfo.path
  if (appliance_type == 'CookProcessor') {
    appId = 'wxec2dafeacbaf5fb5'
    path = '/pages/navigator/loading/loading?landing_type=12&landingPage=pages/navigator/index/index'
  } else {
    // cooking 跳转到家电详情页面
    path = '/pages/navigator/loading/loading?utm_source=hc&landing_type=7'
  }
  return jumpMP(appId, path, params, button_id)
}

/**
 * 获取分享token
 */
export async function loadShareToken(haId: string, type: string) {
  try {
    uni.showLoading({
      title: i18n.global.t('APP.Common.Loading.Text'),
      mask: true,
    })
    let userProfile = uni.getStorageSync('userProfile')
    if (userProfile && userProfile.userName) {
      if (accountStore.ownerName != userProfile.userName) await accountStore.undateOwnerName(userProfile.userName)
      const res1 = await getSharing(haId, type)
      await accountStore.undateSharetoken(res1.data.sharetoken)
    } else {
      await new Promise<void>((resolve) => {
        uni.getUserProfile({
          desc: '完善个人信息，享受更多优质服务',
          success: async (res) => {
            if (accountStore.ownerName != res.userInfo.nickName) {
              await accountStore.undateOwnerName(res.userInfo.nickName)
            }
            uni.setStorageSync('userProfile', res.userInfo)
            const res2 = await getSharing(haId, type)
            await accountStore.undateSharetoken(res2.data.sharetoken)
            resolve()
          },
          fail: async () => {
            const res3 = await getSharing(haId, type)
            await accountStore.undateSharetoken(res3.data.sharetoken)
            resolve()
          },
        })
      })
    }
    uni.hideLoading()
  } catch (error) {
    uni.hideLoading()
    uni.showToast({
      title: '获取shareToken失败',
      icon: 'error',
      duration: 3000,
    })
  }
}

/**
 * 实时获取当前时间
 */
export function useRealTime(nowTimeRef: Ref<number>, nowApplianceTimeRef: Ref<number>) {
  const timer = setInterval(() => {
    nowTimeRef.value += 1000
    nowApplianceTimeRef.value += 1000
  }, 1000)
  const autoTime = computed(() => dayjs(nowTimeRef.value).format('YYYY/MM/DD HH:mm:ss'))
  const applianceTime = computed(() => dayjs(nowApplianceTimeRef.value).format('HH:mm:ss'))
  const clearTimer = () => clearInterval(timer)
  return {
    autoTime,
    applianceTime,
    clearTimer,
  }
}
/**
 * 获取当前年份的日期和周几
 */
export function getCurrentYearDateWeek() {
  let list: string[] = []
  let weeks = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
  let date = new Date()
  let year = date.getFullYear()
  let nowwMonth = date.getMonth() + 1
  let nowDay = date.getDate()
  for (let month = 1; month <= 12; month++) {
    let days = new Date(year, month, 0).getDate()
    for (let day = 1; day <= days; day++) {
      if (nowwMonth == month && nowDay == day) {
        list.push('今天')
      } else {
        list.push(`${month}月${day}日 ` + weeks[new Date(year, month - 1, day).getDay()])
      }
    }
  }
  return list
}
/**
 * 获取某年某月某日是当年的第几天
 * @param date
 * @returns
 */
export function getDayIndex(date: string) {
  let arr = date.split('/')
  let preDate = new Date(Number(arr[0]), 0, 0).getTime()
  let nowwDate = new Date(Number(arr[0]), Number(arr[1]) - 1, Number(arr[2])).getTime()
  let dayIndex = (nowwDate - preDate) / 24 / 60 / 60 / 1000
  return dayIndex
}

/**
 * 生成分享5：4的图片
 */
export function makeCanvas(
  imgUrl: string,
  component: WechatMiniprogram.Component.Instance<any, any, any>
): Promise<string> {
  return new Promise((resolve, reject) => {
    // 获取图片信息,小程序下获取网络图片信息需先配置download域名白名单才能生效
    uni.getImageInfo({
      src: imgUrl,
      success: (imgInfo) => {
        let ctx = uni.createCanvasContext('share-canvas', component)
        let canvasW = 0
        let canvasH = imgInfo.height
        // 把比例设置为 宽比高 5:4
        canvasW = (imgInfo.height * 5) / 4
        // 为画框设置背景色，注意要放在画图前，图会覆盖在背景色上
        ctx.fillStyle = '#fff'
        if (imgInfo.width > 225 || imgInfo.height > 180) {
          canvasW = 225
          canvasH = 180
          ctx.fillRect(0, 0, canvasW, canvasH)
          let dWidth = canvasW / imgInfo.width // canvas与图片的宽度比例
          let dHeight = canvasH / imgInfo.height // canvas与图片的高度比例
          let dWH = imgInfo.width / imgInfo.height //宽高比
          if (imgInfo.width > canvasW && imgInfo.height > canvasH) {
            // console.log(dWH);
            if (dWH > 1 && dWH < 1.5) {
              ctx.drawImage(
                imgInfo.path,
                (canvasW - imgInfo.width * dHeight) / 2,
                0,
                imgInfo.width * dHeight,
                imgInfo.height * dHeight
              )
            } else {
              if (imgInfo.width > imgInfo.height) {
                ctx.drawImage(
                  imgInfo.path,
                  0,
                  (canvasH - imgInfo.height * dWidth) / 2,
                  imgInfo.width * dWidth,
                  imgInfo.height * dWidth
                )
              }
              if (imgInfo.width == imgInfo.height) {
                ctx.drawImage(
                  imgInfo.path,
                  (canvasW - imgInfo.width * dHeight) / 2,
                  0,
                  imgInfo.width * dHeight,
                  imgInfo.height * dHeight
                )
              }
              if (imgInfo.width < imgInfo.height) {
                ctx.drawImage(
                  imgInfo.path,
                  (canvasW - imgInfo.width * dHeight) / 2,
                  0,
                  imgInfo.width * dHeight,
                  imgInfo.height * dHeight
                )
              }
            }
          } else {
            if (imgInfo.width > imgInfo.height) {
              ctx.drawImage(imgInfo.path, 0, (canvasH - imgInfo.height) / 2, imgInfo.width * dWidth, imgInfo.height)
            }
            if (imgInfo.width == imgInfo.height) {
              ctx.drawImage(
                imgInfo.path,
                (canvasW - imgInfo.width * dHeight) / 2,
                0,
                imgInfo.width * dHeight,
                imgInfo.height * dHeight
              )
            }
            if (imgInfo.width < imgInfo.height) {
              ctx.drawImage(
                imgInfo.path,
                (canvasW - imgInfo.width * dHeight) / 2,
                0,
                imgInfo.width * dHeight,
                imgInfo.height * dHeight
              )
            }
          }
        } else {
          ctx.fillRect(0, 0, canvasW, canvasH)
          ctx.drawImage(
            imgInfo.path,
            0,
            0,
            canvasW,
            canvasH,
            (canvasW - imgInfo.width) / 2, // 宽度从中间向两边填充
            0,
            canvasW,
            canvasH
          )
        }

        ctx.draw(false, () => {
          uni.canvasToTempFilePath(
            {
              width: canvasW,
              height: canvasH,
              destWidth: 750, // 标准的iphone6尺寸的两倍，生成高清图
              destHeight: 600,
              canvasId: 'share-canvas',
              fileType: 'png', // 注意jpg默认背景为透明
              success: (res) => {
                resolve(res.tempFilePath)
              },
              fail: (err) => {
                reject(err)
              },
            },
            component
          )
        })
      },
      fail: (err) => {
        reject(err)
      },
    })
  })
}
// 微信小程序系统检测
const res = uni.getSystemInfoSync()
export function checkSystem() {
  let targetVersion = 11 //Ios目标版本号
  let currentVersion = toNumber(res.system.slice(4, 6))

  return currentVersion >= targetVersion
}
export function pairCompare() {
  let version = '7.0.20' //微信目标版本号
  let platform = '微信'
  if ((res as any).environment && (res as any).environment == 'wxwork') {
    platform = '企业微信'
    version = '7.0.4'
  }

  if (compareVersion(res.version, version) > 0) {
    return ''
  } else {
    return '您当前的' + platform + '版本会导致联网失败，请升级至' + version + '版本以上的' + platform + '后再尝试联网'
  }
}
function compareVersion(v1: string, v2: string) {
  const res1 = v1.split('.')
  const res2 = v2.split('.')
  let len = Math.max(res1.length, res2.length)

  while (res1.length < len) {
    res1.push('0')
  }
  while (res2.length < len) {
    res2.push('0')
  }

  for (let i = 0; i < len; i++) {
    let num1 = parseInt(res1[i])
    let num2 = parseInt(res2[i])

    if (num1 > num2) {
      return 1
    } else if (num1 < num2) {
      return -1
    }
  }
  return 0
}
function checkLocationPermission() {}
export async function checkReason() {
  const settingRes = await checkBlutoothPermission()

  const isIos = checkSystem()
  const isPair = pairCompare()
  // ios系统判断
  if (!isIos && res.platform == 'ios') {
    showModal({
      title: i18n.global.t('APP.Common.Tips.Text'),
      content: '为更好使用晶御智能小程序，请升级iOS系统',
      showCancel: false,
      confirmText: '知道了',
    })
    return 0
  } else if (isPair) {
    //微信版本判断
    showModal({
      title: i18n.global.t('APP.Common.Tips.Text'),
      content: isPair,
      showCancel: false,
      confirmText: '知道了',
    })
    return 0
  } else if (settingRes === 'fail') {
    return false
  } else if (settingRes === 'auth_deny') {
    return `${netconfig.ASSETSPRE}/Assets/icons/HC3.0_bluetoothAuthorize.jpg` //蓝牙使用判断
  }

  return true
}
